package br.gendi.dialog;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.PlatformUI;

import br.gendi.beans.BaseGenomica;
import br.gendi.beans.Parametros;
import br.gendi.rcp.NavigationView;

public class ConfiguracoesBases {

	private Shell sShell = null;  //  @jve:decl-index=0:visual-constraint="10,10"
	private TabFolder tabFolder = null;
	private Composite composite = null;
	private Composite composite2 = null;
	private Label label = null;
	private Text text = null;
	private Composite composite1 = null;
	private Button btnSalvar = null;
	private Button btnRemover = null;
	private Label label2 = null;
	private Text text1 = null;
	private Label label1 = null;
	private Button checkBox = null;
	private Label label3 = null;
	private Text text2 = null;
	private BaseGenomica base = null;
	private Composite composite3 = null;

	public ConfiguracoesBases() {
		super();
		createSShell();
	}

	public ConfiguracoesBases(BaseGenomica b) {
		super();
		createSShell();
		text.setText(b.getTitulo());
		text1.setText(b.getUrl());
		text2.setText(b.getFormAction());

		criarCamposVirtuais(b, composite2);
		base = b;
	}

	private void createSShell() {
		GridLayout gridLayout = new GridLayout();
		gridLayout.horizontalSpacing = 2;
		gridLayout.marginWidth = 2;
		gridLayout.marginHeight = 2;
		gridLayout.verticalSpacing = 2;
		sShell = new Shell();
		sShell.setText("Configurações");
		InputStream isLarge = getClass().getClassLoader().getResourceAsStream("icons\\mainicon32.png");
		InputStream isSmall = getClass().getClassLoader().getResourceAsStream("icons\\mainicon16.png");
		
		Image large = new Image(sShell.getDisplay(), isLarge);
		Image small = new Image(sShell.getDisplay(), isSmall);

		sShell.setImages(new Image[] {small, large});
		createTabFolder();
		sShell.setLayout(gridLayout);
		//createComposite3();
		sShell.setSize(600, 400);
		sShell.setMinimumSize(600,400);
		sShell.open();
		this.actions();
	}

	private void actions() {
		btnSalvar.addSelectionListener(new SelectionListener() {
			public void widgetDefaultSelected(SelectionEvent arg0) {

			}
			public void widgetSelected(SelectionEvent arg0) {
				try { 
					base.setTitulo(text.getText());
					File f2 = new File(".\\saves\\");
					if (!f2.exists())
						f2.mkdirs();
					File f = new File(".\\saves\\"+base.getTitulo());
					if (!f.exists())
						f.createNewFile();
					else {
						boolean confirm = MessageDialog.openConfirm(sShell, "configuração existente", "Base com titulo já existente.\n\nClique em 'OK' para sobrescrever.\n'Cancelar' para cancelar o processo.");
						if (confirm != true)
							return;
					}

					ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f)); 
					out.writeObject(base);
					out.flush();
					out.close(); 
				} catch (IOException e) {

				}
				IViewPart[] views = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getViews();
				NavigationView nv = null;
				for (int i=0; i<views.length; i++)
					if (views[i] instanceof NavigationView) {
						nv = (NavigationView) views[i];
						break;
					}
				try {
					nv.carregarItens();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
				MessageDialog.openInformation(sShell, "Salvar", "Configuração da base salva com sucesso.");
			}
		});


	}

	private void createTabFolder() {
		GridData gridData = new GridData();
		gridData.horizontalAlignment = GridData.FILL;
		gridData.grabExcessHorizontalSpace = true;
		gridData.grabExcessVerticalSpace = true;
		gridData.verticalAlignment = GridData.FILL;
		tabFolder = new TabFolder(sShell, SWT.NONE);
		tabFolder.setLayoutData(gridData);
		createComposite();
		createComposite2();
		TabItem tabItem = new TabItem(tabFolder, SWT.NONE);
		tabItem.setText("Geral");
		tabItem.setControl(composite);
		composite.setSize(700, 400);
		TabItem tabItem1 = new TabItem(tabFolder, SWT.NONE);
		tabItem1.setText("Parametros");
		tabItem1.setControl(composite2);
	}

	private void createComposite() {
		GridData gridData8 = new GridData();
		gridData8.grabExcessHorizontalSpace = true;
		gridData8.verticalAlignment = GridData.CENTER;
		gridData8.horizontalSpan = 3;
		gridData8.horizontalAlignment = GridData.FILL;
		GridData gridData7 = new GridData();
		gridData7.grabExcessHorizontalSpace = true;
		gridData7.verticalAlignment = GridData.CENTER;
		gridData7.horizontalSpan = 3;
		gridData7.horizontalAlignment = GridData.FILL;
		GridData gridData6 = new GridData();
		gridData6.horizontalAlignment = GridData.BEGINNING;
		gridData6.verticalAlignment = GridData.CENTER;
		GridData gridData5 = new GridData();
		gridData5.horizontalAlignment = GridData.FILL;
		gridData5.grabExcessHorizontalSpace = true;
		gridData5.horizontalSpan = 3;
		gridData5.verticalAlignment = GridData.CENTER;
		GridData gridData4 = new GridData();
		gridData4.horizontalAlignment = GridData.FILL;
		gridData4.grabExcessHorizontalSpace = true;
		gridData4.horizontalSpan = 3;
		gridData4.verticalAlignment = GridData.CENTER;
		GridData gridData3 = new GridData();
		gridData3.horizontalAlignment = GridData.BEGINNING;
		gridData3.verticalAlignment = GridData.CENTER;
		GridData gridData2 = new GridData();
		gridData2.horizontalAlignment = GridData.BEGINNING;
		gridData2.verticalAlignment = GridData.CENTER;
		GridLayout gridLayout1 = new GridLayout();
		gridLayout1.numColumns = 4;
		composite = new Composite(tabFolder, SWT.NONE);
		composite.setLayout(gridLayout1);
		label = new Label(composite, SWT.NONE);
		label.setText("Nome:");
		label.setLayoutData(gridData3);
		text = new Text(composite, SWT.BORDER);
		text.setLayoutData(gridData5);
		label2 = new Label(composite, SWT.NONE);
		label2.setText("URL:");
		label2.setLayoutData(gridData2);
		text1 = new Text(composite, SWT.BORDER);
		text1.setLayoutData(gridData4);
		label3 = new Label(composite, SWT.NONE);
		label3.setText("Action:");
		text2 = new Text(composite, SWT.BORDER);
		text2.setLayoutData(gridData8);
		label1 = new Label(composite, SWT.NONE);
		label1.setText("Habilitado:");
		label1.setLayoutData(gridData6);
		checkBox = new Button(composite, SWT.CHECK);
		checkBox.setLayoutData(gridData7);
		createComposite3();
		createComposite1();
	}

	private void createComposite2() {
		GridLayout gridLayout4 = new GridLayout();
		gridLayout4.numColumns = 3;
		composite2 = new Composite(tabFolder, SWT.NONE);
		composite2.setSize(new Point(572, 334));
		composite2.setLayout(gridLayout4);
	}

	private void createComposite1() {
		GridData gridData1 = new GridData();
		gridData1.grabExcessHorizontalSpace = true;
		gridData1.horizontalAlignment = GridData.END;
		gridData1.verticalAlignment = GridData.END;
		gridData1.grabExcessVerticalSpace = true;
		GridLayout gridLayout2 = new GridLayout();
		gridLayout2.numColumns = 2;
		gridLayout2.verticalSpacing = 3;
		gridLayout2.marginWidth = 3;
		gridLayout2.marginHeight = 3;
		gridLayout2.horizontalSpacing = 3;
		composite1 = new Composite(composite3, SWT.NONE);
		composite1.setLayout(gridLayout2);
		composite1.setLayoutData(gridData1);
		btnSalvar = new Button(composite1, SWT.NONE);
		btnSalvar.setText("&Salvar");
		btnRemover = new Button(composite1, SWT.NONE);
		btnRemover.setText("&Remover");
	}


	/**
	 * O CODIGO SATANICOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
	 * @param b
	 * @param composite3
	 */
	private void criarCamposVirtuais(BaseGenomica b, Composite composite3) {
		ArrayList<Parametros> a1 = b.getParametros();

		Label label3;
		GridData gridData = new GridData();
		gridData.horizontalAlignment = GridData.FILL_HORIZONTAL;
		gridData.grabExcessHorizontalSpace = true;
		gridData.verticalAlignment = GridData.CENTER;

		final ArrayList<Text> descricoes = new ArrayList<Text>();


		for (int i=0; i < a1.size(); i++) {
			final Parametros p = a1.get(i);

			label3 = new Label(composite3, SWT.NONE);
			label3.setText(p.getNome());
			label3.setToolTipText(p.getTipoCampo());

			if (p.getTipoCampo().equals("text") || p.getTipoCampo().equals("textarea")) { //textarea

				final Text text2 = new Text(composite3, SWT.BORDER);

				if (p.getValorAtual() != null)
					text2.setText(p.getValorAtual());
				else
					if (p.getValorPadrao() != null)
						text2.setText(p.getValorPadrao());

				text2.addModifyListener(new ModifyListener() {
					public void modifyText(ModifyEvent arg0) {
						p.setValorAtual(text2.getText());
					}
				});

			} //textarea 
			else 
				if (p.getTipoCampo().startsWith("select")) { //select
					Combo c;
					if (p.getTipoCampo().equals("select_single")) {
						c = new Combo(composite3, SWT.BORDER | SWT.READ_ONLY | SWT.V_SCROLL);
					}else {
						c = new Combo(composite3, SWT.BORDER | SWT.READ_ONLY | SWT.V_SCROLL | SWT.MULTI);
					}

					Collection _valores = p.getValores();
					for (Iterator _v = _valores.iterator(); _v.hasNext();)
						c.add((String) _v.next());

					if (c.getItemCount() > 0)
						c.select(0);

				}	//select 
				else 	
					if (p.getTipoCampo().startsWith("checkbox"))  { //checkbox
						Button b3 = new Button(composite3, SWT.CHECK);
						b3.addSelectionListener(new SelectionListener() {
							public void widgetDefaultSelected(SelectionEvent arg0) {

							}
							public void widgetSelected(SelectionEvent arg0) {
								Button button = (Button) arg0.widget;
								if (button.getSelection() == true) {
									p.setValorAtual("true");
								} else {
									p.setValorAtual("false");
								}
							}
						});
						if (p.getValorAtual() != null) {
							if (p.getValorAtual().equalsIgnoreCase("true"))
								b3.setSelection(true);
							else
								b3.setSelection(false);
						}

					} //checkbox fim 
					else 
						if (p.getTipoCampo().equals("hidden")) { //hidden
							final Text text2 = new Text(composite3, SWT.BORDER);

							if (p.getValorAtual() != null)
								text2.setText(p.getValorAtual());
							else
								if (p.getValorPadrao() != null)
									text2.setText(p.getValorPadrao());

							text2.setEnabled(false);

						} //hidden
						else if (p.getTipoCampo().equals("file")) { //file
							final Text text2 = new Text(composite3, SWT.BORDER);

							if (p.getValorAtual() != null)
								text2.setText(p.getValorAtual());
							else
								if (p.getValorPadrao() != null)
									text2.setText(p.getValorPadrao());

							text2.addModifyListener(new ModifyListener() {
								public void modifyText(ModifyEvent arg0) {
									p.setValorAtual(text2.getText());
								}
							});

						} //file end
						else if (p.getTipoCampo().startsWith("submit"))  { //submit
							Button b3 = new Button(composite3, SWT.CHECK);
							b3.addSelectionListener(new SelectionListener() {
								public void widgetDefaultSelected(SelectionEvent arg0) {

								}
								public void widgetSelected(SelectionEvent arg0) {
									Button button = (Button) arg0.widget;
									if (button.getSelection() == true) {
										p.setValorAtual("true");
									} else {
										p.setValorAtual("false");
									}
								}
							});
							if (p.getValorAtual() != null) {
								if (p.getValorAtual().equalsIgnoreCase("true"))
									b3.setSelection(true);
								else
									b3.setSelection(false);
							}

						} //submit fim 
						else {
							System.out.println(p.getTipoCampo());
							new Button(composite3, SWT.CHECK);
						}
			GridData gridData6 = new GridData();
			gridData6.horizontalAlignment = GridData.FILL;
			gridData6.grabExcessHorizontalSpace = true;
			gridData6.verticalAlignment = GridData.CENTER;
			Text text3 = new Text(composite3, SWT.BORDER);
			text3.setLayoutData(gridData6);
			text3.addModifyListener(new ModifyListener() {
				public void modifyText(ModifyEvent arg0) {
					ArrayList<Parametros> par = null;
					Text t = null;

					for (int i=0;i < descricoes.size(); i++) {
						if (descricoes.get(i) == arg0.widget) {
							par = base.getParametros();
							t = (Text) arg0.widget;
							par.get(i).setDescricao(t.getText());
						}
					}
				}
			});

			try {
				text3.setText(p.getDescricao());
			} catch (Exception e) {
				continue;
			}

			descricoes.add(text3);
		} //fim do for
	}

	private void createComposite3() {
		GridData gridData9 = new GridData();
		gridData9.horizontalAlignment = GridData.FILL;
		gridData9.grabExcessHorizontalSpace = true;
		gridData9.verticalAlignment = GridData.CENTER;
		GridLayout gridLayout3 = new GridLayout();
		gridLayout3.horizontalSpacing = 1;
		gridLayout3.marginWidth = 1;
		gridLayout3.marginHeight = 1;
		gridLayout3.verticalSpacing = 1;
		composite3 = new Composite(sShell, SWT.NONE);
		composite3.setLayout(gridLayout3);
		composite3.setLayoutData(gridData9);
	}
}
